﻿namespace FFF.Test.Application.DomainServices.FW
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Abp.Domain.Services;
    using Abp.Domain.Uow;
    using Abp.EntityFrameworkCore.Uow;
    using Abp.EntityFrameworkCore;
    using AutoMapper;
    using Abp.UI;
    using Ydm.Helper;
    using Ydm.Extensions;
    using Microsoft.EntityFrameworkCore;
    using AutoMapper.QueryableExtensions;
    using FFF.Test.DataAccess.Framework;
    using FFF.Test.Application.Repositories.FW;
    using FFF.Test.Entity.FW;
    using FFF.Test.Entity.FW.Dto;
    using FFF.Test.Entity.FW.View;

    /// <summary>
    /// 企业权限中间表领域层服务接口
    /// </summary>
    public class FWCompany2ActionDomainService : YdmAbpDomainServiceBase, IFWCompany2ActionDomainService
    {
        /// <summary>
        /// 企业权限中间表仓储
        /// </summary>
        private readonly IFWCompany2ActionRepository _fWCompany2ActionRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="FWCompany2ActionDomainService"/> class.
        /// 企业权限中间表领域层操作
        /// </summary>
        /// <param name="fWCompany2ActionRepository">企业权限中间表仓储</param>
        public FWCompany2ActionDomainService(
            IFWCompany2ActionRepository fWCompany2ActionRepository
        )
        {
            this._fWCompany2ActionRepository = fWCompany2ActionRepository;
        }

        /// <summary>
        /// 1._0_010 获取用户佣金信息(于大明,掌中宴)
        /// </summary>
        /// <param name="inDto">获取用户佣金信息输入dto</param>
        /// <returns>获取用户佣金信息输出dto</returns>
        public async Task<BatchSaveBuActionOutDto> BatchSaveBuActionAsync(BatchSaveBuActionInDto inDto)
        {
            var result = new BatchSaveBuActionOutDto();
            var viewFwBu2action = this._fWCompany2ActionRepository.GetView()
              .Where(x => x.CompanyGUID == inDto.CompanyGUID && x.ApplicationGUID == inDto.ApplicationGUID);

            // 先批量删除
            await this._fWCompany2ActionRepository.GetAll()
                .Where(x => viewFwBu2action.Any(y => y.Id == x.Id)).DeleteFromQueryAsync();

            // 如果有父级GUID那么也需要保存
            var entitys = inDto.ActionIds.Select(actionGUID => new FWCompany2ActionEntity()
            {
                Id = Guid.NewGuid(),
                ActionGUID = actionGUID,
                CompanyGUID = inDto.CompanyGUID,
                CreateTime = DateTime.Now
            });

            await this._fWCompany2ActionRepository.GetDbContext().BulkInsertAsync(entitys);
            return result;
        }
    }
}
